<template>
  <div class="user-info-container">
    <div class="page-card">
      <div class="page-header">
        <h2>个人信息</h2>
        <el-button type="primary" @click="handleUpdateProfile" size="small">
          编辑个人信息
        </el-button>
      </div>
      
      <div class="user-info-content" v-if="!loading && userData">
        <div class="user-avatar-section">
          <el-avatar :size="120" :src="userAvatar">{{ userData.姓名?.[0] || '用' }}</el-avatar>
          <h3 class="user-name">{{ userData.姓名 || '未设置姓名' }}</h3>
          <p class="user-role">角色：{{ getUserRoleText() }}</p>
        </div>
        
        <div class="user-details-section">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户ID">
              {{ userData.id || '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="手机号">
              {{ userData.手机号 || '未设置手机号' }}
            </el-descriptions-item>
            <el-descriptions-item label="身份证号">
              {{ userData.身份证号 || '未设置身份证号' }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱">
              {{ userData.邮箱 || '未设置邮箱' }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatDate(userData.created_at) }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              {{ formatDate(userData.updated_at) || '从未更新' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      
      <div class="loading-container" v-else-if="loading">
        <el-skeleton :rows="10" animated />
      </div>
      
      <div class="error-container" v-else>
        <el-empty description="无法加载用户信息" :image-size="120">
          <el-button type="primary" @click="fetchUserData">重新加载</el-button>
        </el-empty>
      </div>
    </div>
    
    <!-- 编辑个人信息对话框 -->
    <el-dialog
      v-model="showUpdateDialog"
      title="编辑个人信息"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="updateForm" :rules="updateRules" ref="updateFormRef" label-width="100px">
        <el-form-item label="姓名" prop="姓名">
          <el-input v-model="updateForm.姓名" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="手机号">
          <el-input v-model="updateForm.手机号" placeholder="请输入手机号" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="邮箱">
          <el-input v-model="updateForm.邮箱" placeholder="请输入邮箱"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showUpdateDialog = false">取消</el-button>
        <el-button type="primary" @click="submitUpdate" :loading="updating">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { userAPI } from '../api'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const updating = ref(false)
const userData = ref(null)
const showUpdateDialog = ref(false)
const updateFormRef = ref(null)

// 表单数据
const updateForm = reactive({
  姓名: '',
  手机号: '',
  邮箱: ''
})

// 表单验证规则
const updateRules = {
  姓名: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  邮箱: [
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ]
}

// 用户头像颜色
const userAvatar = computed(() => {
  // 基于用户ID生成不同颜色的头像
  const avatarColors = ['#409eff', '#67c23a', '#e6a23c', '#f56c6c', '#909399']
  const userId = userData.value?.id || 0
  return avatarColors[userId % avatarColors.length]
})

// 获取用户角色文本
const getUserRoleText = () => {
  const userRole = localStorage.getItem('userRole')
  const roleMap = {
    'admin': '管理员',
    'user': '普通用户'
  }
  return roleMap[userRole] || '未知角色'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN')
  } catch {
    return dateString
  }
}

// 获取用户数据
const fetchUserData = async () => {
  try {
    loading.value = true
    
    // 从localStorage获取当前用户ID
    const userInfoStr = localStorage.getItem('userInfo')
    let userId = null
    
    if (userInfoStr) {
      try {
        const userInfo = JSON.parse(userInfoStr)
        userId = userInfo.user_id || userInfo.id
      } catch (error) {
        console.error('解析用户信息失败:', error)
      }
    }
    
    // 如果localStorage中没有用户信息，尝试从路由参数获取
    if (!userId && route.params.id) {
      userId = route.params.id
    }
    
    // 如果还是没有用户ID，提示用户登录
    if (!userId) {
      ElMessage.error('未找到用户信息，请重新登录')
      router.push('/login')
      return
    }
    
    // 调用API获取用户信息
    const response = await userAPI.getUserInfo(userId)
    
    // 检查响应是否为数组（因为json-server可能返回数组）
    if (Array.isArray(response) && response.length > 0) {
      userData.value = response[0]
    } else {
      userData.value = response
    }
    
    if (!userData.value) {
      throw new Error('未找到用户信息')
    }
    
    // 更新localStorage中的用户信息
    localStorage.setItem('userInfo', JSON.stringify(userData.value))
    
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败: ' + (error.message || '未知错误'))
    userData.value = null
  } finally {
    loading.value = false
  }
}

// 打开编辑对话框
const handleUpdateProfile = () => {
  if (userData.value) {
    // 复制用户数据到表单
    updateForm.姓名 = userData.value.姓名 || ''
    updateForm.手机号 = userData.value.手机号 || ''
    updateForm.邮箱 = userData.value.邮箱 || ''
    showUpdateDialog.value = true
  }
}

// 提交更新
const submitUpdate = async () => {
  try {
    await updateFormRef.value.validate()
    updating.value = true
    
    // 准备更新数据
    const updateData = {
      ...userData.value,
      ...updateForm
    }
    
    // 调用API更新用户信息（这里使用模拟实现，因为userAPI中没有update方法）
    // 实际项目中应该调用专门的update方法
    console.log('更新用户信息:', updateData)
    
    // 模拟成功响应
    setTimeout(() => {
      // 更新本地数据
      userData.value = updateData
      // 更新localStorage
      localStorage.setItem('userInfo', JSON.stringify(updateData))
      
      ElMessage.success('个人信息更新成功')
      showUpdateDialog.value = false
    }, 1000)
    
  } catch (error) {
    console.error('更新个人信息失败:', error)
    ElMessage.error('更新失败: ' + (error.message || '未知错误'))
  } finally {
    updating.value = false
  }
}

// 页面加载时获取用户数据
onMounted(() => {
  fetchUserData()
})
</script>

<style scoped>
.user-info-container {
  min-height: 100vh;
  background-color: #FFFFFF;
  padding: 20px;
}

.page-card {
  background: #FFFFFF;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e0e0e0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e0e0e0;
}

.page-header h2 {
  margin: 0;
  color: #333333;
  font-size: 20px;
}

.user-info-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.user-avatar-section {
  text-align: center;
  margin-bottom: 32px;
}

.user-name {
  margin-top: 16px;
  margin-bottom: 8px;
  font-size: 24px;
  color: #333333;
}

.user-role {
  color: #606266;
  font-size: 14px;
  margin: 0;
}

.user-details-section {
  width: 100%;
  max-width: 800px;
}

.loading-container,
.error-container {
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-descriptions-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-descriptions-item__content) {
  color: #303133;
}

:deep(.el-descriptions__border) {
  background-color: #FFFFFF;
}

:deep(.el-descriptions__header) {
  padding-bottom: 12px;
  margin-bottom: 16px;
  border-bottom: 1px solid #e0e0e0;
}

:deep(.el-descriptions-item) {
  padding: 12px 16px;
}

:deep(.el-descriptions-item__label.is-bordered-label) {
  background-color: #f5f7fa;
  border-right: 1px solid #e0e0e0;
}

:deep(.el-descriptions-item__content.is-bordered-content) {
  border-right: 1px solid #e0e0e0;
}

:deep(.el-descriptions-item.is-last-column .el-descriptions-item__label.is-bordered-label),
:deep(.el-descriptions-item.is-last-column .el-descriptions-item__content.is-bordered-content) {
  border-right: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-info-container {
    padding: 10px;
  }
  
  .page-card {
    padding: 16px;
  }
  
  .user-details-section {
    :deep(.el-descriptions) {
      :deep(.el-descriptions-item) {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
      }
    }
  }
}
</style>